import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'
import request from '../../../utils/request'

import getCurrentCity from '../../../utils/currentCity'

import styles from './index.module.css'

export default class Search extends Component {
  // 当前城市id

  state = {
    // 搜索框的值
    searchTxt: '',
    tipsList: [],
    time: null
  }
  async componentDidMount  () {
    this.cityId = await getCurrentCity()
  }
  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state

    return tipsList.map(item => (
      <li key={item.community} className={styles.tip} onClick={_ => this.props.history.push({
        pathname: '/rent/add',
        state: {
          c: item
        }
      })}>
        {item.communityName}
      </li>
    ))
  }
  onChange = (val) => { // 双向绑定状态，和模糊搜索功能
    this.setState(_ => { // 将受控组件绑定的数据放到state状态中
      return {
        searchTxt: val
      }
    })
    if (!val) { // 搜索框为空，清除列表，不在发送请求
      return this.setState({
        tipsList: []
      })
    }
    
    clearTimeout(this.time) // 每次清除上一次的定时器
    this.time = setTimeout( async _ => { // 定时器挂载到组件实例身上
      const { data: res } = await request('/area/community', 'GET', {
        params: {
          name: val,
          id: this.cityId.value
        }
      })
      if (res.status === 200) {
        this.setState({
          tipsList: res.body
        })
      }
    }, 500)
    
    
  }

  render() {
    const { history } = this.props
    const { searchTxt } = this.state

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          placeholder="请输入小区或地址"
          value={searchTxt}
          showCancelButton={true}
          onChange={this.onChange}
          onCancel={() => history.replace('/rent/add')}
        />

        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    )
  }
}
